package com.cat.dataStructure;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/count-submatrices-with-top-left-element-and-sum-less-than-k/
 * @create 2025/8/20 16:04
 * @since JDK17
 */

public class Solution41 {
    int n, m;
    int[][] arr;

    int sum(int a, int b, int c, int d) {
        return arr[c + 1][d + 1] - arr[c + 1][b] - arr[a][d + 1] + arr[a][b];
    }

    public int countSubmatrices(int[][] mat, int k) {
        n = mat.length;
        m = mat[0].length;
        arr = new int[n + 1][m + 1];
        for (int a = 1, b = 0; b < n; a++, b++) {
            for (int c = 1, d = 0; d < m; c++, d++) {
                arr[a][c] = mat[b][d];
            }
        }
        for (int i = 1; i <= n; i++) {  // 制作前缀和数组
            for (int j = 1; j <= m; j++) {
                arr[i][j] += arr[i - 1][j] + arr[i][j - 1] - arr[i - 1][j - 1];
            }
        }
        int ans = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (sum(0, 0, i, j) <= k) {
                    ans++;
                }
            }
        }
        return ans;
    }
}
